package com.basker.pisces.springcloud.rpc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.basker.pisces.core.rpx.RpcContext;
import com.basker.pisces.core.rpx.RpcContextHolder;
import com.basker.pisces.service.constant.ServiceConstants;
import com.basker.pisces.springcloud.utils.RequestUtils;

public class ServiceRpcContexctInterceptor extends HandlerInterceptorAdapter {

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        RpcContext rpcContext = RpcContextHolder.getRpcContext();
        if (rpcContext != null) {
            RpcContextHolder.remove();
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String sourceAppId = RequestUtils.getHeader(ServiceConstants.MessageHead.APP_ID_KEY, true);

        RpcContext rpcContext = new RpcContext();
        rpcContext.setSourceAppId(sourceAppId);

        RpcContextHolder.setRpcContext(rpcContext, true);

        return true;
    }
}
